package com.credithc.eagleeye.api.utils;
import com.credithc.eagleeye.api.config.WXWorkConfig;
import com.credithc.eagleeye.util.FastJsonConvert;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
/**
 * 描 述: <br/>
 * 作 者: zhangjin<br/>
 * 创 建：2019年11月20日<br/>
 * 版 本：v1.0.0<br>
 * <p>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
@Component
@Slf4j
public class WXWorkUtils {
    private WXWorkConfig wxWorkConfig;

    private String API_URL_TEXT;
    private String API_URL_CARD;
    private String API_URL_IMAGE;
    private String API_URL_MPNEWS;
    private String API_KEY;

    public static void main(String[] args) {
        WXWorkConfig wxWorkConfig = new WXWorkConfig();
        wxWorkConfig.setApiKey("c3b37e21754cdbafa624dca68246669bcddc2c85");
        wxWorkConfig.setApiUrl("http://10.10.255.196/api/v2/qywxsend");
        wxWorkConfig.setEagleEyeSysUrl("http://mail.credithc.com");
        WXWorkUtils wxWorkUtils = new WXWorkUtils(wxWorkConfig);
        String text = "鹰眼-[多乐融每2分钟异常报警]:<br>" +
                "统计时间范围:[2019-11-20 13:57:22]至[2019-11-20 13:59:22],\n" +
                "触发了[多乐融每2分钟异常报警]规则,涉及总计条数：10条。\n" +
                "第1条：\n" +
                "traceId:779ee85ddf144db9bb05ac43c33d2f23,\n" +
                "平台名称:dlr,\n" +
                "客户端:account-ice,\n" +
                "服务名:httpClientUtils,\n" +
                "方法名:postJson,\n" +
                "结果:ERROR,\n" +
                "耗时:0,\n" +
                "返回值:org.apache.http.NoHttpResponseException: 10.10.255.198:80 failed to respond\n" +
                "第2条：\n" +
                "traceId:779ee85ddf144db9bb05ac43c33d2f23,\n" +
                "平台名称:dlr,\n" +
                "客户端:account-ice,\n" +
                "服务名:httpClientUtils,\n" +
                "方法名:postJson,\n" +
                "结果:ERROR,\n" +
                "耗时:0,\n" +
                "返回值:org.apache.http.NoHttpResponseException: 10.10.255.198:80 failed to respond\n" +
                "第3条：\n" +
                "traceId:779ee85ddf144db9bb05ac43c33d2f23,\n" +
                "平台名称:dlr,\n" +
                "客户端:account-ice,\n" +
                "服务名:httpClientUtils,\n" +
                "方法名:postJson,\n" +
                "结果:ERROR,\n" +
                "耗时:0,\n" +
                "返回值:org.apache.http.NoHttpResponseException: 10.10.255.198:80 failed to respond\n" +
                "";
        //boolean retText = wxWorkUtils.sendText("zhangjin150415@credithc.com", text);
        //System.out.println(retText);
        String body = "<div class='gray'>统计时间范围:2019-11-20 13:57:22至2019-11-20 13:59:22</div><div class='highlight'>触发了[多乐融每2分钟异常报警]规则,涉及总计条数：1条。</div>";
        boolean retCard = wxWorkUtils.sendCard("zhangjin150415@credithc.com","鹰眼-[多乐融每2分钟异常报警]","",body);
        //System.out.println(retCard);
    }

    public WXWorkUtils(WXWorkConfig wxWorkConfig) {
        this.wxWorkConfig = wxWorkConfig;
        API_URL_TEXT = String.format("%s/text", wxWorkConfig.getApiUrl());
        API_URL_CARD = String.format("%s/textcard", wxWorkConfig.getApiUrl());
        API_URL_IMAGE = String.format("%s/image", wxWorkConfig.getApiUrl());
        API_URL_MPNEWS = String.format("%s/mpnews", wxWorkConfig.getApiUrl());
        API_KEY = wxWorkConfig.getApiKey();
    }

    /**
     * 发送企业微信文本消息
     *
     * @param receiver 企业邮箱，持逗号分隔
     * @param text     文本消息
     */
    public boolean sendText(String receiver, String text) {
        if (StringUtils.isBlank(receiver)) {
            return false;
        }
        String[] receivers = StringUtils.split(receiver, ",");
        return sendText(receivers, text);
    }

    public boolean sendText(String[] receivers, String text) {
        TextVo textVo = new TextVo();
        textVo.setKey(API_KEY);
        textVo.setTo(fixReceivers(receivers));
        textVo.setBody(text);
        try {
            String json = HttpClientUtil.postJson(API_URL_TEXT, FastJsonConvert.convertObjectToJSON(textVo), "UTF-8");
            //log.info(json);
            ResultVo resultVo = FastJsonConvert.convertJSONToObject(json, ResultVo.class);
            if (resultVo != null && resultVo.getCode() == 200) {
                return true;
            }
        } catch (IOException e) {
        }
        return false;
    }

    private String[] fixReceivers(String[] receivers) {
        String[] address = new String[receivers.length];
        for(int i = 0; i < receivers.length; i++) {
            String receiver = receivers[i];
            if (!StringUtils.endsWithIgnoreCase(receiver, "@credithc.com")) {
                address[i] += receiver + "@credithc.com";
            }else {
                address[i] = receiver;
            }
        }
        return address;
    }

    /**
     * 发送企业微信卡片消息
     * @param receiver 企业邮箱，持逗号分隔
     * @param subject  标题，不超过128个字节，超过会自动截断
     * @param body     文本内容，支持换行\n、以及<a/>标签
     */
    public boolean sendCard(String receiver,String subject, String alertLogId,String body) {
        if (StringUtils.isBlank(receiver)) {
            return false;
        }
        String[] receivers = StringUtils.split(receiver, ",");
        return sendCard(receivers, subject,this.wxWorkConfig.getEagleEyeSysUrl()+alertLogId,body,"");
    }
    /**
     * 发送企业微信卡片消息
     * @param receivers 企业邮箱，持逗号分隔
     * @param subject  标题，不超过128个字节，超过会自动截断
     * @param url      点击后跳转的链接
     * @param body     文本内容，支持换行\n、以及<a/>标签
     * @param btntxt   按钮文字。 默认为“详情”， 不超过4个文字，超过自动截断。
     */
    public boolean sendCard(String[] receivers, String subject, String url, String body, String btntxt) {
        CardVo cardVo = new CardVo();
        cardVo.setKey(API_KEY);
        cardVo.setTo(fixReceivers(receivers));
        cardVo.setSubject(subject);
        cardVo.setUrl(url);
        cardVo.setBody(body);
        cardVo.setBtntxt(btntxt);
        try {
            String json = HttpClientUtil.postJson(API_URL_CARD, FastJsonConvert.convertObjectToJSON(cardVo), "UTF-8");
            log.info(json);
            ResultVo resultVo = FastJsonConvert.convertJSONToObject(json, ResultVo.class);
            if (resultVo != null && resultVo.getCode() == 200) {
                return true;
            }
        } catch (IOException e) {

        }
        return false;
    }
}
@Data
class TextVo {
    private String key;
    private String[] to;
    private String body;
}
@Data
class CardVo {
    private String key;
    private String[] to;
    private String subject;
    private String url;
    private String body;
    private String btntxt;
}
@Data
class ResultVo{
    private String message;
    private Integer code;
}
